package com.chagee.store.operation.server.service.biz;

import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chagee.store.operation.api.enums.ForewarningTypeEnum;
import com.chagee.store.operation.api.enums.IdentifyImageLocationEnum;
import com.chagee.store.operation.common.constant.SupplierWorkOrderConstant;
import com.chagee.store.operation.server.entity.TaskExecutionDO;
import com.chagee.store.operation.server.entity.WorkOrderDO;
import com.chagee.store.operation.server.event.service.TaskExecutionBaseService;
import com.chagee.store.operation.server.event.service.WorkOrderBaseService;
import com.chagee.store.operation.server.model.param.StoreIssueNoticeParam;
import com.chagee.store.operation.api.response.vo.AiResultVO;
import com.chagee.store.operation.server.model.vo.TaskPicPushVO;
import com.chagee.store.operation.server.service.BaiduAiIdentifyService;
import com.chagee.store.operation.server.service.StoreAppSweepService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName WorkOrderAIService  //类名称
 * @Description: //类描述
 * @Author: Jacky-zhan	//作者
 * @CreateDate: 2024/9/3 11:30	//创建时间
 * @UpdateUser: Jacky-zhan  //变更者
 * @UpdateDate: 2024/9/3 11:30	//更新时间
 * @UpdateRemark: //更新的信息
 * @Version: 1.0    //版本号
 */
@Slf4j
@Component
public class WorkOrderAIService {

	@Value("${work-order.taskName:智能茶饮机}")
	private String taskName;

	@Value("${ai-result.unqualifiedDesc}")
	private String aiResultDesc;

	@Resource
	private TaskExecutionBaseService taskExecutionBaseService;

	@Resource
	private WorkOrderBaseService workOrderBaseService;

	@Resource
	private StoreAppSweepService storeAppSweepService;

	@Resource
	private BaiduAiIdentifyService baiduAiIdentifyService;

	/**
	 * 调用ai大数据模型处理图片
	 *
	 * @param taskExecutionDO 任务信息
	 * @param takePictures    待校验的图片信息
	 */
	@Async("workOrderAISyncExecutor")
	public void dealWorkOrderAIPhoto(TaskExecutionDO taskExecutionDO, List<AiResultVO> takePictures) {
		List<AiResultVO> pictureInfoVOS = new ArrayList<>();
		log.info("dealWorkOrderAIPhoto_taskExecutionDO：{}, takePictures:{}", JSON.toJSONString(taskExecutionDO),JSON.toJSONString(takePictures));
		if (CollectionUtils.isNotEmpty(takePictures)) {
			//  验证AI返回的结果，只验证 智能茶饮机
			if (StringUtils.isNotBlank(taskName)) {
				List<String> stringList = Arrays.asList(taskName.split(SupplierWorkOrderConstant.COMMA));
				if (stringList.contains(taskExecutionDO.getTaskName())) {
					boolean flag = false;
					for (AiResultVO fileVO : takePictures) {
						//只针对：出茶口TEA_OUTLET/料仓SILO/出风口OUTLET/蠕动泵PERISTALTIC_PUMP/门框滑轨DOOR_FRAME_SLIDING_RAIL/茶饮机表面TEA_DRINKING_MACHINE_SURFACE 这几个位置进行AI验收
						if (StringUtils.isNotBlank(fileVO.getType())) {
							//请求失败code集合
							List<String> fileNoList = SupplierWorkOrderConstant.AI_RESPONSE_FAIL_NO_CODE;
							//出茶口请求成功但是不合格code，
							List<String> teaOutletAiSuccessCodeList = SupplierWorkOrderConstant.TEA_OUTLET_AI_SUCCESS_CODE;
							//料仓请求成功但是不合格code，
							List<String> siloAiSuccessCodeList = SupplierWorkOrderConstant.SILO_AI_SUCCESS_CODE;
							//出风口请求成功但是不合格code，
							List<String> outletAiSuccessCodeList = SupplierWorkOrderConstant.OUTLET_AI_SUCCESS_CODE;
							//蠕动泵请求成功但是不合格code，
							List<String> peristalticPumpAiSuccessCodeList = SupplierWorkOrderConstant.PERISTALTIC_PUMP_AI_SUCCESS_CODE;

							if (IdentifyImageLocationEnum.TEA_OUTLET.getType().equals(fileVO.getType())) {
								//调用ai大数据的接口，将返回的合格不合格结果进行处理。
								log.info("工单编号{}的{}的任务的{}位置获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName(), IdentifyImageLocationEnum.TEA_OUTLET.getDesc());
								AiResultVO aiResultVO = getAiResultVO(fileVO, fileNoList);
								if (CollectionUtils.isNotEmpty(teaOutletAiSuccessCodeList) && teaOutletAiSuccessCodeList.contains(aiResultVO.getCode().toString())) {
									//如果是20005
									//if (SupplierWorkOrderConstant.TEA_OUTLET_AI_SUCCESS_CODE_05.equals(aiResultVO.getCode().toString())) {
										pictureInfoVOS.add(fileVO);
										flag = true;
									//}
									log.info("请求成功，不合格图片的地址：{}", fileVO.getFilePath());
								}
							} else if (IdentifyImageLocationEnum.SILO.getType().equals(fileVO.getType())) {
								//调用ai大数据的接口，将返回的合格不合格结果进行处理。
								log.info("工单编号{}的{}的任务的{}位置获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName(), IdentifyImageLocationEnum.SILO.getDesc());
								AiResultVO aiResultVO = getAiResultVO(fileVO, fileNoList);
								if (CollectionUtils.isNotEmpty(siloAiSuccessCodeList) && siloAiSuccessCodeList.contains(aiResultVO.getCode().toString())) {
									//如果是20031
									//if (SupplierWorkOrderConstant.SILO_AI_SUCCESS_CODE_31.equals(aiResultVO.getCode().toString())) {
										pictureInfoVOS.add(fileVO);
										flag = true;
									//}
									log.info("请求成功，不合格图片的地址：{}", fileVO.getFilePath());
								}
							} else if (IdentifyImageLocationEnum.OUTLET.getType().equals(fileVO.getType())) {
								//调用ai大数据的接口，将返回的合格不合格结果进行处理。
								log.info("工单编号{}的{}的任务的{}位置获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName(), IdentifyImageLocationEnum.OUTLET.getDesc());
								AiResultVO aiResultVO = getAiResultVO(fileVO, fileNoList);
								if (CollectionUtils.isNotEmpty(outletAiSuccessCodeList) && outletAiSuccessCodeList.contains(aiResultVO.getCode().toString())) {
									//如果是20012
									//if (SupplierWorkOrderConstant.OUTLET_AI_SUCCESS_CODE_12.equals(aiResultVO.getCode().toString())) {
										pictureInfoVOS.add(fileVO);
										flag = true;
									//}
									log.info("请求成功，不合格图片的地址：{}", fileVO.getFilePath());
								}
							} else if (IdentifyImageLocationEnum.PERISTALTIC_PUMP.getType().equals(fileVO.getType())) {
								//调用ai大数据的接口，将返回的合格不合格结果进行处理。
								log.info("工单编号{}的{}的任务的{}位置获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName(), IdentifyImageLocationEnum.PERISTALTIC_PUMP.getDesc());
								AiResultVO aiResultVO = getAiResultVO(fileVO, fileNoList);
								if (CollectionUtils.isNotEmpty(peristalticPumpAiSuccessCodeList) && peristalticPumpAiSuccessCodeList.contains(aiResultVO.getCode().toString())) {
									//如果是20022
									//if (SupplierWorkOrderConstant.PERISTALTIC_PUMP_AI_SUCCESS_CODE_22.equals(aiResultVO.getCode().toString())) {
										pictureInfoVOS.add(fileVO);
										flag = true;
									//}
									log.info("请求成功，不合格图片的地址：{}", fileVO.getFilePath());
								}
							} else if (IdentifyImageLocationEnum.DOOR_FRAME_SLIDING_RAIL.getType().equals(fileVO.getType())) {
								log.info("工单编号{}的{}的任务获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName());
							} else if (IdentifyImageLocationEnum.TEA_DRINKING_MACHINE_SURFACE.getType().equals(fileVO.getType())) {
								log.info("工单编号{}的{}的任务获取ai识别开始", taskExecutionDO.getWorkOrderNumber(), taskExecutionDO.getTaskName());
							}
							log.info("fileVO:{}", JSON.toJSONString(fileVO));
						}
					}
					taskExecutionDO.setTakePictures(JSON.toJSONString(takePictures));
					//flag = true时表示存在AI识别结果存在不干净的图片，
					if (flag) {
						taskExecutionDO.setAiResult(SupplierWorkOrderConstant.AI_RESULT_NO);
					}
					log.info("dealWorkOrderAIPhoto_taskExecutionDO_aiResult：{}", JSON.toJSONString(taskExecutionDO));
					taskExecutionBaseService.update(taskExecutionDO);
				}
			}
		}
		// 当图片AI结果为不合格时需发送消息通知
		/*if (SupplierWorkOrderConstant.AI_RESULT_NO.equals(taskExecutionDO.getAiResult())) {
			//获取工单信息
			LambdaQueryWrapper<WorkOrderDO> workOrderDoQueryWrapper = new LambdaQueryWrapper<>();
			workOrderDoQueryWrapper.eq(StringUtils.isNotBlank(taskExecutionDO.getWorkOrderNumber()), WorkOrderDO::getWorkOrderNumber,
				taskExecutionDO.getWorkOrderNumber()).eq(WorkOrderDO::getDeleteFlag, NumberUtils.INTEGER_ZERO);
			WorkOrderDO workOrderDO = workOrderBaseService.getOne(workOrderDoQueryWrapper);
			if (Objects.nonNull(workOrderDO)) {
				StoreIssueNoticeParam storeIssueNoticeParam = new StoreIssueNoticeParam();
				storeIssueNoticeParam.setStoreNo(workOrderDO.getStoreCode());
				storeIssueNoticeParam.setId(String.valueOf(taskExecutionDO.getId()));
				storeIssueNoticeParam.setIssueType(ForewarningTypeEnum.ORDER_ACCEPTANCE_FOREWARNING.getType());
				storeIssueNoticeParam.setIssueDescription(aiResultDesc);
				List<TaskPicPushVO> picPushVOS = takePictures.stream().filter(t -> StringUtils.isNotBlank(t.getType())).map(s -> {
					TaskPicPushVO taskPicPushVO = new TaskPicPushVO();
					BeanUtils.copyProperties(s, taskPicPushVO);
					if (StringUtils.isNotEmpty(s.getType())) {
						taskPicPushVO.setLocationName(IdentifyImageLocationEnum.getByType(s.getType()).getDesc());
					}
					return taskPicPushVO;
				}).collect(Collectors.toList());
				Map<String, Object> hashMap = new HashMap<>();
				hashMap.put("allPicList", picPushVOS);
				hashMap.put("pictureInfoList", pictureInfoVOS);
				storeIssueNoticeParam.setExtData(JSONObject.toJSONString(hashMap));
				log.info("AI智能校验图片结果不合格时发送消息通知开始。");
				storeAppSweepService.sendMessage(storeIssueNoticeParam);
			}
		}*/
	}

	/**
	 * AI识别并赋值
	 *
	 * @param fileVO     图片对象
	 * @param fileNoList 失败数组
	 * @return AI识别结果
	 */
	private AiResultVO getAiResultVO(AiResultVO fileVO, List<String> fileNoList) {
		log.info("开始调用百度AI模型");
		HttpResponse httpResponse = baiduAiIdentifyService.dealWorkOrderAI(fileVO.getType(), fileVO.getFilePath());
		log.info("开始对ai识别结果信息解析，赋值");
		AiResultVO aiResultVO = baiduAiIdentifyService.parseResultResponse(httpResponse.body());
		fileVO.setCode(Objects.nonNull(aiResultVO.getCode()) ? aiResultVO.getCode() : null);
		fileVO.setMessage(StringUtils.isNotBlank(aiResultVO.getMessage()) ? aiResultVO.getMessage() : null);
		fileVO.setItemCount(Objects.nonNull(aiResultVO.getItemCount()) ? aiResultVO.getItemCount() : null);
		if (CollectionUtils.isNotEmpty(aiResultVO.getItems())) {
			fileVO.setItems(aiResultVO.getItems());
		}
		//请求成功
		if (SupplierWorkOrderConstant.AI_RESPONSE_SUCCESS_OK_CODE.equals(aiResultVO.getCode().toString())) {
			log.info("请求成功，合格图片的地址：{}", fileVO.getFilePath());
		}
		if (CollectionUtils.isNotEmpty(fileNoList) && fileNoList.contains(aiResultVO.getCode().toString())) {
			log.info("请求失败，不合格图片的地址：{}", fileVO.getFilePath());
		}
		return aiResultVO;
	}

}
